package com.tf8.treasure.support.beans.autoconfig;

import com.tf8.treasure.support.beans.BeanMapperHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Order(Ordered.LOWEST_PRECEDENCE - 1)
public class BeanMapperAutoConfigurationImportSelector implements ImportBeanDefinitionRegistrar {
    private static Logger log = LoggerFactory.getLogger(BeanMapperAutoConfigurationImportSelector.class);

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        Map<String, Object> attrs = metadata.getAnnotationAttributes(
                BeanMapperEnableAutoConfiguration.class.getName(), true);
        if(CollectionUtils.isEmpty(attrs)){
            log.error("BeanMapperAutoConfiguration 用法错误");
            return;
        }
        Object basePackage = attrs.get("basePackage");
        if(basePackage == null || "".equals(basePackage)){
            log.error("BeanMapperAutoConfiguration basePackage 为空");
            return;
        }
        registerClientConfiguration(registry,(String)basePackage);
    }

    private void registerClientConfiguration(BeanDefinitionRegistry registry,String basePackage) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(BeanMapperHelper.class);
        builder.addPropertyValue("basePackage",basePackage);
        registry.registerBeanDefinition("beanMapper", builder.getBeanDefinition());
    }

}